﻿using System;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using ReportWizard.Entities;
using ReportWizard.Helpers;

namespace ReportWizard.Controls
{
    public partial class PhotoListDetails : UserControl
    {
        public ReportImageFileList PhotoSet { get; set; }

        public PhotoListDetails(ReportImageFileList photoSet)
        {
            InitializeComponent();

            PhotoSet = photoSet;
        }

        private void FillPhotoList()
        {
            if (PhotoSet != null)
            {
                ListViewItem[] photoList = new ListViewItem[PhotoSet.Photos.Count];

                for (int i = 0; i < PhotoSet.Photos.Count; i++)
                {
                    Image currentImage = Image.FromFile(PhotoSet.Photos[i].FilePath);

                    photoList[i] = new ListViewItem(PhotoSet.Photos[i].FileName)
                                        {
                                            Tag = PhotoSet.Photos[i],
                                            Checked = PhotoSet.Photos[i].Checked
                                        };
                    photoList[i].SubItems.Add(PhotoSet.Photos[i].Description);
                    photoList[i].SubItems.Add(string.Format("{0} x {1}", currentImage.Width, currentImage.Height));
                }
                lvFileList.Items.AddRange(photoList);
            }
        }

        private void PhotoListLoad(object sender, EventArgs e)
        {
            FillPhotoList();
        }

        private void PhotoListItemChecked(object sender, ItemCheckedEventArgs e)
        {
            ReportImageFile rfi = (ReportImageFile)e.Item.Tag;
            if (rfi != null)
            {
                ReportImageFile selectedItem = PhotoSet.Photos.Where(i => i.FilePath.Equals(rfi.FilePath)).FirstOrDefault();
                if (selectedItem != null)
                    selectedItem.Checked = e.Item.Checked;
            }
        }

        private void PhotoListSelectedIndexChanged(object sender, EventArgs e)
        {
            if (lvFileList.FocusedItem != null && lvFileList.FocusedItem.Tag != null)
            {
                pbPreview.ImageLocation = ((ReportImageFile)lvFileList.FocusedItem.Tag).FilePath;
            }
        }

        private void PhotoListDoubleClick(object sender, EventArgs e)
        {
            if (lvFileList.FocusedItem != null && lvFileList.FocusedItem.Tag != null)
            {
                try
                {
                    Process.Start(((ReportImageFile)lvFileList.FocusedItem.Tag).FilePath);
                }
                catch (Exception ex)
                {
                    Logger.WriteLog(ex);
                }
            }
        }
    }
}
